package com.medusa.aps.business.util;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.medusa.aps.business.model.exception.BusinessErrorCode;
import com.medusa.aps.business.global.model.exception.GlobalException;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author xh.yu
 * @since 2023/07/10 15:07
 */
@Slf4j
public class ExcelUtils {

    /**
     * @param errorMap     总异常信息Map
     * @param rowIndex     行数
     * @param errorMessage 异常字符串
     */
    public static void handlerErrorMessage(Map<Long, StringBuilder> errorMap, Long rowIndex, String errorMessage) {
        errorMap.merge(rowIndex, new StringBuilder(errorMessage), (existing, toAdd) -> existing.append(StrUtil.COMMA).append(toAdd));
    }

    /**
     * 错误信息返回
     *
     * @param errorMap 校验异常的信息
     */
    public static void validErrorMessageData(Map<Long, StringBuilder> errorMap) {
        if (MapUtil.isNotEmpty(errorMap)) {
            String errorMessage = errorMap.entrySet().stream()
                    .map(entry -> StrUtil.format("第" + entry.getKey() + "行，" + entry.getValue()))
                    .collect(Collectors.joining("、"));
            throw new GlobalException(BusinessErrorCode.PARAMETER_ERROR.getCode(), errorMessage);
        }
    }

}
